<template>
<div style="padding:5px">
    <el-button type="primary" style="margin-bottom:5px"  size="small" @click="add">添加按钮</el-button>
    <el-dialog title="添加按钮" v-model="outerVisible" append-to-body draggable>
      <el-form  ref="inputForm" label-width="140px" :model="form">
        <el-form-item label="名称" prop="name" :rules="[
                {required: true, message:'名称不能为空', trigger:'blur'}
                 ]"> 
          <el-input v-model="form.name">
             <el-button  @click="openSelectButton" icon="search">快速添加</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="编码" prop="code" :rules="[
                {required: true, message:'编码不能为空', trigger:'blur'}
                 ]">
          <el-input v-model="form.code"></el-input>
        </el-form-item>
       <el-form-item label="排序" prop="sort" :rules="[
                {required: true, message:'排序不能为空', trigger:'blur'}
                 ]">
        <el-input-number v-model="form.sort" style="width:100%" label="排序"></el-input-number>
        </el-form-item>
        <el-form-item label="是否隐藏" prop="isHide" :rules="[
                {required: true, message:'必选项不能为空', trigger:'blur'}
                 ]">
          <el-select v-model="form.isHide" style="width:100%" placeholder="请选择">
            <el-option
              v-for="item in [{
                value: '0',
                label: '否'
              },{
                value: '1',
                label: '是'
              }]"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="下一节点审核人" prop="next" :rules="[
                {required: true, message:'必选项不能为空', trigger:'blur'}
                 ]">
          <el-select style="width:100%" v-model="form.next" placeholder="请选择">
            <el-option
             v-for="item in [{
                value: '0',
                label: '不能手动设置'
              },{
                value: '1',
                label: '能手动设置'
              }]"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer class="dialog-footer">
        <el-button  @click="outerVisible = false">取 消</el-button>
        <el-button  type="primary" @click="save">确定</el-button>
      </template>
    </el-dialog>
    <el-table
      :data="tableData"
      border
      >
      <el-table-column
        prop="name"
        label="名称"
        width="80">
      </el-table-column>
      <el-table-column
        prop="code"
        label="编码"
        width="80">
      </el-table-column>
      <el-table-column
        prop="sort"
        label="排序"
         width="80">
      </el-table-column>
      <el-table-column
        prop="isHide"
        label="是否隐藏"
         width="80">
          <template #default="scope">
          {{scope.row.isHide === '0' ? '否':'是'}}
        </template>
      </el-table-column>
       <el-table-column
        prop="next"
        label="下一节点审核人">
          <template #default="scope">
          {{scope.row.isHide === '0' ? '不能手动设置':'可以手动设置'}}
        </template>
      </el-table-column>
       <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="100"
        label="操作">
        <template #default="scope">
          <el-button text 
                     @click="edit(scope.row)">
            修改
          </el-button>
          <el-button  text  @click="del(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <buttons-select @selectButton="selectButton" ref="buttonSelect"/>
</div>
</template>

  <script>
    import pick from 'lodash.pick'
    import ButtonsSelect from './ButtonsSelect.vue'
import elementHelper from 'jp-bpmn-js-properties-panel/lib/helper/ElementHelper'
import find from 'lodash/find'
import { is } from 'jeeplus-bpmn/lib/util/ModelUtil'
import { getBusinessObject } from 'jeeplus-bpmn/lib/util/ModelUtil'
export default {
      props: {
        element: {
          type: Object,
          default: undefined
        },
        bpmnModeler: {
          type: Object,
          default: undefined
        }
      },
      components: {
        ButtonsSelect
      },
      data () {
        return {
          outerVisible: false,
          oldRow: null,
          form: {
            name: '',
            code: '',
            isHide: '0',
            next: '0',
            sort: 0
          },
          tableData: []
        }
      },
      methods: {
        add () {
          this.outerVisible = true
          this.oldRow = null
          this.$nextTick(() => {
            this.$refs['inputForm'].resetFields()
          })
        },
        edit (row) {
          this.outerVisible = true
          this.oldRow = row
          this.form = JSON.parse(JSON.stringify(row))
        },
        openSelectButton () {
          this.$refs.buttonSelect.visible = true
        },
        selectButton (button) {
          this.form.name = button.name
          this.form.code = button.code
          this.form.sort = button.sort
        },
        save () {
          this.$refs['inputForm'].validate((valid) => {
            if (valid) {
              if (this.oldRow === null) {
                this.tableData.push(JSON.parse(JSON.stringify(this.form)))
              } else {
                this.tableData.forEach((item, index) => {
                  if (item === this.oldRow) {
                    this.tableData.splice(index, 1, this.form)
                  }
                })
              }
              this.outerVisible = false
            }
          })
        },
        del (row) {
          this.tableData.forEach((item, index) => {
            if (item === row) {
              this.tableData.splice(index, 1)
            }
          })
        },
        getExtensionElements (element) {
          let bo = getBusinessObject(element)
          return bo.extensionElements
        },
        createExtensionElements: function (element, bo) {
          var extensionElements = elementHelper.createElement('bpmn:ExtensionElements', { values: [] }, bo, this.bpmnModeler.get('bpmnFactory'))
          bo.extensionElements = extensionElements
          return extensionElements
        },
        isExtensionElements (element) {
          return is(element, 'bpmn:ExtensionElements')
        },
        getButtonsElement (element) {
          if (!this.isExtensionElements(element)) {
            return element.buttons
          } else {
            return this.getButtonsElementInsideExtensionElements(element)
          }
        },
        getButtonsElementInsideExtensionElements (extensionElements) {
          return find(extensionElements.values, function (elem) {
            return is(elem, 'flowable:Button')
          })
        },
        updateElements (tableDatas) {
          let element = this.element
          let bo = getBusinessObject(element)
          let parent = this.getExtensionElements(element)

          if (!parent && typeof this.createExtensionElements === 'function') {
            parent = this.createExtensionElements(element, bo)
          //  commands.push(result.cmd)
          }
          // var buttons = this.getButtonsElement(parent)
          // if (!buttons) {
          //   buttons = elementHelper.createElement('flowable:Buttons', {}, parent, this.bpmnModeler.get('bpmnFactory'))
          //   if (!this.isExtensionElements(parent)) {
          //     this.bpmnModeler.get('modeling').updateBusinessObject(element, parent, { 'buttons': buttons })
          //   //  commands.push(cmdHelper.updateBusinessObject(element, parent, { 'buttons': buttons }))
          //   } else {
          //     this.bpmnModeler.get('commandStack').execute('properties-panel.update-businessobject-list', {
          //       element: element,
          //       currentObject: parent,
          //       propertyName: 'values',
          //       referencePropertyName: 'extensionElements',
          //       objectsToAdd: [ buttons ],
          //       objectsToRemove: []
          //     })
          //   }
          // }

        //  var buttonProps = {id: 'abc', name: 'def'}
        //  forEach(modelProperties, function (prop) {
        //    buttonProps[prop] = undefined
        //  })
        //  if (modelProperties.indexOf('id') >= 0) {
        //    buttonProps.id = generateButtonId()
        //  }
          let objList = []
          tableDatas.forEach((row) => {
            var button = elementHelper.createElement('flowable:Button', row, parent, this.bpmnModeler.get('bpmnFactory'))
            objList.push(button)
          })

          let old = []
          if (this.element.businessObject.extensionElements) {
            this.element.businessObject.extensionElements.values.forEach((value) => {
              if (is(value, 'flowable:Button')) {
                old.push(value)
              }
            })
          }
          this.bpmnModeler.get('commandStack').execute('properties-panel.update-businessobject-list', {
            element: element,
            currentObject: parent,
            propertyName: 'values',
            objectsToRemove: old
          })

          this.bpmnModeler.get('commandStack').execute('properties-panel.update-businessobject-list', {
            element: element,
            currentObject: parent,
            propertyName: 'values',
            objectsToAdd: objList
          })
        }
      },
      watch: {
        tableData: {
          handler (newVal) {
            if (this.element) {
              this.updateElements(newVal)
            }
          },
          deep: true
        },
        'element': {
          handler (newVal) {
            this.tableData = []
            if (this.element.businessObject.extensionElements) {
              this.element.businessObject.extensionElements.values.forEach((value) => {
                if (is(value, 'flowable:Button')) {
                  value = pick(value, 'id', 'name', 'sort', 'isHide', 'code', 'next')
                  this.tableData.push(JSON.parse(JSON.stringify(value)))
                }
              })
            }
          },
          immediate: true,
          deep: false
        }
      }
}
  </script>